package com.woniu.cq.medical.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniu.cq.medical.common.Result;
import com.woniu.cq.medical.config.AlipayConfig;
import com.woniu.cq.medical.controller.form.CheckApplyForm;
import com.woniu.cq.medical.service.CheckApplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2020-09-05
 */
@Controller
@RequestMapping("/medical/check-apply")
@CrossOrigin("*")//解决跨域问题
@Slf4j
public class CheckApplyController {

    private static String PRODUCT_PAY = "药品支付";
    private static String PROJECT_PAY = "检查费用";
    private static String REGISTER_PAY = "挂号费用";

    @Autowired
    private CheckApplyService checkApplyService;

    @ResponseBody
    @RequestMapping("insertCheckApply")
    public Result insertCheckApply(CheckApplyForm checkApplyForm) {
        checkApplyService.insertCheckApply(checkApplyForm);
        return Result.success();
    }

    @RequestMapping("productPay")
    public void productPay( HttpServletRequest request, HttpServletResponse response){
        String money = request.getParameter("productTotal");
        String[] prescriptionIds = request.getParameterValues("prescriptionId");
        String patientIdCard = request.getParameter("patientIdCard");
        String str="";
        for(String prescriptionId:prescriptionIds){
            str+=(prescriptionId+"-");
        }
        str+=patientIdCard;
        System.out.println(str);
        String orderId=UUID.randomUUID().toString().replace("-", "");
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = orderId;
            //付款金额，必填

            String total_amount = money;
            //订单名称，必填
            String subject =PRODUCT_PAY;


            //商品描述，可空
            String body = "";
            String passback_params =URLEncoder.encode(str,"UTF-8");

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"passback_params\":\""+passback_params+"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //		+ "\"total_amount\":\""+ total_amount +"\","
            //		+ "\"subject\":\""+ subject +"\","
            //		+ "\"body\":\""+ body +"\","
            //		+ "\"timeout_express\":\"10m\","
            //		+
            //"\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求

            //输出
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(out_trade_no);
            out.println(result);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    /**
     * 支付宝接口方法 必须封装成表单 传入money patientIdCard
     * @param request
     * @param response
     */
    @RequestMapping("RegisterPay")
    public void REgisterPay( HttpServletRequest request,HttpServletResponse response){
        String money = request.getParameter("money");
        String patientIdCard = request.getParameter("patientIdCard");
        String str=""+patientIdCard;
        System.out.println(str);
        String orderId=UUID.randomUUID().toString().replace("-", "");
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = orderId;
            //付款金额，必填

            String total_amount = money;
            //订单名称，必填
            String subject =REGISTER_PAY;


            //商品描述，可空
            String body = "";
            String passback_params =URLEncoder.encode(str,"UTF-8");

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"passback_params\":\""+passback_params+"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //		+ "\"total_amount\":\""+ total_amount +"\","
            //		+ "\"subject\":\""+ subject +"\","
            //		+ "\"body\":\""+ body +"\","
            //		+ "\"timeout_express\":\"10m\","
            //		+
            //"\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求

            //输出
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(out_trade_no);
            out.println(result);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    @RequestMapping("projectPay")
    public void projectPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String money = request.getParameter("projectTotal");
        String[] checkApplyIds = request.getParameterValues("checkApplyId");
        String patientIdCard = request.getParameter("patientIdCard");
        String str="";
        for(String checkApplyId:checkApplyIds){
            str+=(checkApplyId+"-");
        }
        str+=patientIdCard;
        System.out.println(str);
        String orderId=UUID.randomUUID().toString().replace("-", "");
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = orderId;
            //付款金额，必填

            String total_amount = money;
            //订单名称，必填
            String subject =PROJECT_PAY;


            //商品描述，可空
            String body = "";
            String passback_params =URLEncoder.encode(str,"UTF-8");

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"passback_params\":\""+passback_params+"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //		+ "\"total_amount\":\""+ total_amount +"\","
            //		+ "\"subject\":\""+ subject +"\","
            //		+ "\"body\":\""+ body +"\","
            //		+ "\"timeout_express\":\"10m\","
            //		+
            //"\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求

            //输出
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(out_trade_no);
            out.println(result);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }



    /**
     * 回调接口
     * @param req
     * @param response
     * @throws IOException
     */
    @RequestMapping("payAll")
    public void payAll(HttpServletRequest req, HttpServletResponse response)throws IOException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = req.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified=false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        System.out.println("开始验签!");
        if(signVerified) {
            //验证成功
            //商户订单号
            String out_trade_no = new String(req.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(req.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(req.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            //订单名称
            String subject = req.getParameter("subject");
            String passback_params = req.getParameter("passback_params");
            System.out.println("订单状态"+trade_status);
            System.out.println(subject);
            System.out.println(passback_params);
            if (trade_status.equals("TRADE_SUCCESS")){
                if(subject.equals(PRODUCT_PAY)){
                    checkApplyService.updateProduct(passback_params);
                }
                if(subject.equals(PROJECT_PAY)){
                    checkApplyService.updateProject(passback_params);
                }
                if(subject.equals(REGISTER_PAY)){
                    checkApplyService.updateRegister(passback_params);
                }


            }else {
                System.out.println("订单交易失败!");
            }
        }else {
            System.out.println("验签失败!");
        }
    }




}

